package inet.app.vod.activity.account;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

public class PasswordChangeActivity extends BaseActivity {

	private EditText mOldPassEdt;
	private EditText mNewPassEdt;
	private EditText mRetypeNewPassEdt;
	private View mErrorView;
	
	private String mOldPass;

	View.OnClickListener changePassListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			boolean cancel = validateField();
			if (cancel) {
				mErrorView.requestFocus();
				return;
			} 

			// send new password to register activity
			String pwd = mNewPassEdt.getText().toString();
			Intent returnIntent = new Intent();
			returnIntent.putExtra("result", pwd);
			setResult(RESULT_OK, returnIntent);
			finish();
		}
	};

	private void initModels() {
		Bundle bundle = getIntent().getExtras();
		mOldPass = bundle.getString("old_pass");
	}

	private boolean validateField() {
		boolean cancel = false;
		mOldPassEdt.setError(null);
		mNewPassEdt.setError(null);
		mRetypeNewPassEdt.setError(null);

		// Check valid old password
		String oldPwd = mOldPassEdt.getText().toString();
		if (!oldPwd.equals(mOldPass)) {
			mOldPassEdt.setError("Không đúng mật khẩu cũ");
			mErrorView = mOldPassEdt;
			cancel = true;
			return cancel;
		}

		// Check valid new password
		String newPwd = mNewPassEdt.getText().toString();
		if (TextUtils.isEmpty(newPwd) || newPwd.length() < 6) {
			mNewPassEdt.setError(getString(R.string.mat_khau_it_nhat_6_ki_tu));
			mErrorView = mNewPassEdt;
			cancel = true;
			return cancel;
		}

		String reNewPwd = mRetypeNewPassEdt.getText().toString();
		if (!reNewPwd.equals(newPwd)) {
			mRetypeNewPassEdt
					.setError(getString(R.string.mat_khau_khong_trung_nhau));
			mErrorView = mRetypeNewPassEdt;
			cancel = true;
			return cancel;
		}

		return cancel;
	}

	private void initViews() {
		mOldPassEdt = (EditText) findViewById(R.id.oldpass_edt);
		mNewPassEdt = (EditText) findViewById(R.id.newpass_edt);
		mRetypeNewPassEdt = (EditText) findViewById(R.id.retype_newpass_edt);
		findViewById(R.id.change_pass_btn).setOnClickListener(
				changePassListener);
		setTitle(getResources().getString(R.string.doi_mat_khau));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_password);
		initUIBase();
		initModels();
		initViews();
	}

	@Override
	public void setTagMenu() {
		mTagMenu = -1;
	}

}
